package com.inspur.edp.formserver.vmmanager.lowcode;

import com.inspur.edp.bef.bizentity.GspBusinessEntity;
import com.inspur.edp.cef.entity.config.CefConfig;
import com.inspur.edp.bff.engine.core.cache.BffEngineCacheService;
import com.inspur.edp.formserver.viewmodel.GspViewModel;
import com.inspur.edp.formserver.viewmodel.extendinfo.api.GspVoExtendInfoService;
import com.inspur.edp.formserver.viewmodel.extendinfo.entity.GspVoExtendInfo;
import com.inspur.edp.formserver.viewmodel.extendinfo.entity.VoConfigCollectionInfo;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataPackage;
import com.inspur.edp.lcm.metadata.api.entity.ProcessMode;
import com.inspur.edp.lcm.metadata.spi.event.MdPkgChangedArgs;
import com.inspur.edp.lcm.metadata.spi.event.MdPkgChangedEventListener;
import com.inspur.edp.metadata.rtcustomization.api.CustomizationService;
import io.iec.edp.caf.boot.context.CAFContext;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.core.context.ICAFContextService;
import io.iec.edp.caf.core.session.CafSession;
import io.iec.edp.caf.core.session.ICafSessionService;
import io.iec.edp.caf.core.session.SessionType;
import io.iec.edp.caf.core.session.core.CAFSessionThreadHolder;
import io.iec.edp.caf.tenancy.api.ITenantService;
import io.iec.edp.caf.tenancy.api.entity.Tenant;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MdPkgDeployListener implements MdPkgChangedEventListener {

  CustomizationService metadataService;

  public MdPkgDeployListener() {
    this.metadataService = SpringBeanUtils.getBean(CustomizationService.class);
  }

  @Override
  public void fireMdPkgAddedEvent(MdPkgChangedArgs mdPkgChangedArgs) {
//    if(metadataService == null) {
//      this.metadataService = SpringBeanUtils.getBean(CustomizationService.class);
//    }
//    MetadataPackage metadataPackage = mdPkgChangedArgs.getMetadataPackage();
//    handleMdPkg(metadataPackage, var -> metadataService.getMetadata(var));
  }

  @Override
  public void fireMdPkgChangedEvent(MdPkgChangedArgs mdPkgChangedArgs) {
    if(metadataService == null) {
      this.metadataService = SpringBeanUtils.getBean(CustomizationService.class);
    }
    MetadataPackage metadataPackage = mdPkgChangedArgs.getMetadataPackage();
    clearVoCache(metadataPackage,metadataService);
    //handleMdPkg(metadataPackage, var -> metadataService.getMetadata(var));
  }
  public void clearVoCache( MetadataPackage metadataPackage,CustomizationService metadataService){

    List<GspMetadata> packageMetadataList = metadataPackage.getMetadataList();
    if (packageMetadataList == null || packageMetadataList.isEmpty()) {
      return;
    }
    List<GspMetadata> metadatas = packageMetadataList.stream()
        .filter(item -> item.getHeader().getType().equals("GSPBusinessEntity"))
        .collect(Collectors.toList());
    if (metadatas.isEmpty()) {
      return;
    }
    ArrayList<String> metadataLists=new ArrayList<>();
    GspVoExtendInfoService service = SpringBeanUtils.getBean(GspVoExtendInfoService.class);
    for (GspMetadata metadata: metadatas){
      List<GspVoExtendInfo> voExtendInfos=service.getVoId(metadata.getHeader().getId());
      if(voExtendInfos==null || voExtendInfos.size()==0){
        continue;
      }
      voExtendInfos.forEach(info -> metadataLists.add(info.getId()));
    }

    metadataService.removeCacheByMetadataIds(metadataLists);

  }

//  void handleMdPkg(MetadataPackage metadataPackage,
//      Function<String, GspMetadata> getMetadata) {
//    try {
////      if (metadataPackage.getHeader().getProcessMode() != ProcessMode.interpretation) {
////        //如果不是无需生成代码的元数据包，直接忽略
////        return;
////      }
//
//      List<GspMetadata> packageMetadataList = metadataPackage.getMetadataList();
//      if (packageMetadataList == null || packageMetadataList.isEmpty()) {
//        //如果元数据包下不存在元数据
//        return;
//      }
//      List<GspMetadata> metadatas = packageMetadataList.stream()
//          .filter(item -> item.getHeader().getType().equals("GSPViewModel"))
//          .collect(Collectors.toList());
//      if (metadatas.isEmpty()) {
//        return;
//      }
//      ProcessMode processMode = Optional.ofNullable(metadataPackage.getHeader().getProcessMode()).orElse(ProcessMode.generation);
//      BSessionUtil.wrapFirstTenantBSession(tenant -> {
//        // 获取当前已部署的eapi版本，并移除未变动的Eapi元数据
//        GspVoExtendInfoService beInfoService = SpringBeanUtils
//            .getBean(GspVoExtendInfoService.class);
//        List<GspVoExtendInfo> infos = new ArrayList(metadatas.size());
//        for (GspMetadata metadata : metadatas) {
//          GspViewModel be = (GspViewModel) getMetadata.apply(metadata.getHeader().getId())
//              .getContent();
//            ((GspViewModel) getMetadata.apply(metadata.getHeader().getId()).getContent())
//                .getCoreAssemblyInfo().getDefaultNamespace();
//          BffEngineCacheService.remove(be.getID());
//          if (be.getGeneratedConfigID() == null) {
//            continue;
//          }
//          GspVoExtendInfo existing = beInfoService.getVoExtendInfo(be.getID());
//          GspVoExtendInfo info = buildVoExtendInfo(processMode, be, existing);
//          infos.add(info);
//        }
//        if (!infos.isEmpty()) {
//          beInfoService.saveGspVoExtendInfos(infos);
//        }
//      });
//    } catch (Exception e) {
//      throw new RuntimeException("部署解析VO元数据出错：", e);
//    }
//  }
//
//  private GspVoExtendInfo buildVoExtendInfo(ProcessMode processMode, GspViewModel be, GspVoExtendInfo existing) {
//    GspVoExtendInfo info = new GspVoExtendInfo();
//    VoConfigCollectionInfo voConfigCollectionInfo = getBffConfigCollectionInfo(be);
//    voConfigCollectionInfo.setProjectType(processMode);
//    info.setVoConfigCollectionInfo(voConfigCollectionInfo);
//    info.setId(be.getID());
//    info.setConfigId(be.getGeneratedConfigID());;
//    info.setCreatedOn(Date.from(CAFContext.current.getCurrentDateTime().toInstant()));
//    info.setLastChangedOn(Date.from(CAFContext.current.getCurrentDateTime().toInstant()));
//    if (!be.getIsVirtual()) {
//      info.setBeSourceId(be.getMapping().getTargetMetadataId());
//    }
//    if (existing != null) {
//      info.setLastChangedOn(Date.from(CAFContext.current.getCurrentDateTime().toInstant()));
//    }
//    return info;
//  }
//
//  private VoConfigCollectionInfo getBffConfigCollectionInfo(GspViewModel be) {
//    CefConfig cefConfig = new CefConfig();
//    cefConfig.setID(be.getGeneratedConfigID());
//    cefConfig.setDefaultNamespace(be.getCoreAssemblyInfo().getDefaultNamespace().toLowerCase());
//    VoConfigCollectionInfo voConfigCollectionInfo = new VoConfigCollectionInfo();
//    voConfigCollectionInfo.setConfig(cefConfig);
//    return voConfigCollectionInfo;
//  }
}
